﻿// 
// 创建人：宋欣
// 创建时间：2015-02-13
// 功能： 一般处理程序基类
// Copyright (c) 2014 宋欣. All rights reserved.
// 

using System;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using HBMS.Model;
using Newtonsoft.Json.Linq;

namespace HBMS.Web
{
    public class BaseHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        ///     操作
        /// </summary>
        public string Action { get; set; }

        /// <summary>
        ///     输出结果
        /// </summary>
        public string WriteResult { get; set; }

        /// <summary>
        ///     请求上下文
        /// </summary>
        public HttpContext Context { get; set; }


        /// <summary>
        ///     页索引
        /// </summary>
        public Model.Pagination Pager { get; set; }

        /// <summary>
        ///     登录用户的全局信息
        /// </summary>
        public CurrentUser GoalUserInfo
        {
            get { return GoalUserInfoConfig.GetGoalUserInfo(); }
        }


        public bool IsReusable
        {
            get { return false; }
        }

        public virtual void ProcessRequest(HttpContext context)
        {
            this.Context = context;
            Pager = new Pagination();
            ////页索引
            if (!string.IsNullOrEmpty(context.Request.Params["page"]))
            {
                Pager.PageIndex = Convert.ToInt32(context.Request.Params["page"]);
            }
            ////请求类型
            if (!string.IsNullOrEmpty(context.Request.Params["action"]))
            {
                this.Action = context.Request.Params["action"];
            }
        }

        /// <summary>
        ///     输出结果
        /// </summary>
        public void ResponseWrite()
        {
            Context.Response.Clear();
            Context.Response.Write(WriteResult);
            Context.Response.Flush();
        }


        /// <summary>
        ///     返回nodata数据
        /// </summary>
        /// <returns></returns>
        public string NoDataJson()
        {
            JObject json = new JObject
                {
                    {"data", ""},
                };
            return json.ToString();
        }

        /// <summary>
        ///     返回nodata数据
        /// </summary>
        /// <returns></returns>
        public string JsonSuccess()
        {
            JObject json = new JObject
                {
                    {"result", "1"},
                };
            return json.ToString();
        }

        /// <summary>
        ///     返回nodata数据
        /// </summary>
        /// <returns></returns>
        public string JsonError(string error = "")
        {
            JObject json = new JObject
                {
                    {"result", "0"},
                    {"error", error}
                };
            return json.ToString();
        }

        /// <summary>
        ///     拼接实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public void TryUpdateModel<T>(T t)
        {
            Type type = t.GetType();
            PropertyInfo[] pi = type.GetProperties();
            object val = null;
            foreach (
                var p in
                    pi.Where(
                        p =>
                        Context.Request.Params[p.Name] != null && !string.IsNullOrEmpty(Context.Request.Params[p.Name]))
                )
            {
                ////给一个对象属性赋值可以通过PropertyInfo.SetValue()方式进行赋值，但要注意值的类型要与属性保持一致。   
                ////不确定目标类型，如何进行类型转换。
                val = Context.Request.Params[p.Name];
                if (!p.PropertyType.IsGenericType)
                {
                    p.SetValue(t,
                               val != null && string.IsNullOrEmpty(val.ToString())
                                   ? null
                                   : Convert.ChangeType(Context.Request.Params[p.Name], p.PropertyType), null);
                }
                else
                {
                    //泛型Nullable<>
                    Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof (Nullable<>))
                    {
                        p.SetValue(t,
                                   val != null && string.IsNullOrEmpty(val.ToString())
                                       ? null
                                       : Convert.ChangeType(val, Nullable.GetUnderlyingType(p.PropertyType)), null);
                    }
                }
            }
        }
    }
}